package com.bestv.search.management.command;

import com.bestv.search.common.dataSource.DataSourceKey;
import com.bestv.search.common.model.SubType;
import com.bestv.search.common.model.SysUser;
import com.bestv.search.common.model.Type;
import com.bestv.search.common.service.SubTypeManager;
import com.bestv.search.common.service.TypeManager;
import com.bestv.search.common.util.CommandException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class SubTypeCommand {
    protected final Log log = LogFactory.getLog(getClass());
    private SubTypeManager subTypeManager;
    private TypeManager typeManager;

    public String find(SysUser user, Map<String, String[]> map, DataSourceKey dsKey) throws CommandException {
        String result = "";

        List<SubType> lists = subTypeManager.getSubTypes(dsKey);
        try {
            JSONArray jsonArray = subTypesToJson(lists);
            result = "{'subTypes':" + jsonArray.toString() + "}";
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            log.error(e);
            throw new CommandException();
        }
        return result;
    }

    public String findComm(SysUser user, Map<String, String[]> map, DataSourceKey dsKey) throws CommandException {
        String result = "";
        String[] typeName = map.get("typename");

        SubType subType = subTypeManager.getSubTypeByName(dsKey, typeName[0]);
        try {
            JSONArray jsonArray = new JSONArray();
            jsonArray.put(subTypeToJson(subType));
            result = "{'subTypes':" + jsonArray.toString() + "}";
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            log.error(e);
            throw new CommandException();
        }
        return result;
    }

    public String delete(SysUser user, Map<String, String[]> map, DataSourceKey dsKey) {
        String result = "";
        String[] id = map.get("id");

        if ("".equals(id[0]))
            return "{'result':'failure','message':'idnull'}";
        if ("HDQ".equals(user.getSite().getCode())) {
            subTypeManager.deleteSubType(dsKey, new Long(id[0]));
            result = "{'result':'success','message':''}";
        } else {
            result = "{'result':'failure','message':'noright'}";
        }
        return result;
    }

    public String get(SysUser user, Map<String, String[]> map, DataSourceKey dsKey) throws CommandException {
        String result = "";
        String[] id = map.get("id");

        SubType type = subTypeManager.getSubTypeById(dsKey, new Long(id[0]));
        if (type == null)
            result = "[null]";
        else {
            try {
                JSONObject jsonObj = subTypeToJson(type);
                if (type.getParent() != null)
                    jsonObj.put("parentId", type.getParent().getId());
                result = jsonObj.toString();
            } catch (JSONException e) {
                log.error(e);
                throw new CommandException();
            }
        }
        return result;
    }

    public String save(SysUser user, Map<String, String[]> map, DataSourceKey dsKey) {
        String result = "";
        String[] id = map.get("id");
        String[] name = map.get("typeName");
        String[] description = map.get("typeDescription");
        String[] parentId = map.get("parentid");

        Type parent = null;
        if (!"".equals(parentId[0]))
            parent = typeManager.getTypeById(dsKey, new Long(parentId[0]));
        SubType stype = null;
        if ("".equals(id[0])) {// new
            stype = new SubType();
            stype.setName(name[0]);
            stype.setDescription(description[0]);
            stype.setId(0L);
            if (parent != null)
                stype.setParent(parent);
            subTypeManager.saveSubType(dsKey, stype);
            result = "{'result':'success','message':'new'}";
        } else {// edit
            stype = subTypeManager.getSubTypeById(dsKey, new Long(id[0]));
            if (stype == null)
                stype = new SubType();
            stype.setName(name[0]);
            stype.setDescription(description[0]);
            if (parent != null)
                stype.setParent(parent);
            subTypeManager.saveSubType(dsKey, stype);
            result = "{'result':'success','message':'edit'}";
        }
        return result;
    }

    private JSONObject subTypeToJson(SubType t) throws JSONException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", t.getId());
        jsonObject.put("name", t.getName());
        jsonObject.put("description", t.getDescription());
        if (t.getParent() != null)
            jsonObject.put("parent", t.getParent().getName());
        return jsonObject;
    }

    private JSONArray subTypesToJson(List<SubType> subTypes) throws JSONException {
        List<JSONObject> list = new ArrayList<JSONObject>();
        for (SubType t : subTypes) {
            list.add(subTypeToJson(t));
        }
        JSONArray jsonArray = new JSONArray(list.toArray());
        return jsonArray;
    }

    public SubTypeManager getSubTypeManager() {
        return subTypeManager;
    }

    public void setSubTypeManager(SubTypeManager subTypeManager) {
        this.subTypeManager = subTypeManager;
    }

    public TypeManager getTypeManager() {
        return typeManager;
    }

    public void setTypeManager(TypeManager typeManager) {
        this.typeManager = typeManager;
    }
}
